package com.st.buy.manager.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.st.buy.manager.mapper.TbItemDescMapper;
import com.st.buy.manager.service.ItemService;
import com.st.buy.manager.mapper.TbItemMapper;
import com.st.buy.pojo.TbItem;
import com.st.buy.pojo.TbItemDesc;
import com.st.buy.util.pojo.BuyResult;
import com.st.buy.util.pojo.EasyUIDatagrideVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author 张双虎
 */
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private TbItemMapper itemMapper;
    @Autowired
    private TbItemDescMapper itemDescMapper;
    @Override
    //定制事务特性
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
    public BuyResult save(TbItem item, String desc) {
        //商品的id如何生成  毫秒数+随机数.
        long itemId = System.currentTimeMillis()+(new Random().nextInt(90)+10);
        //补全商品信息
        item.setId(itemId);
        Date time = new Date();
        item.setCreated(time);
        item.setUpdated(time);
        item.setStatus(1);
        //保存
        int insert = itemMapper.insert(item);
        if(insert==1){
            //保存商品详情信息
            TbItemDesc itemDesc = new TbItemDesc();
            itemDesc.setCreated(time);
            itemDesc.setUpdated(time);
            itemDesc.setItemId(itemId);
            itemDesc.setItemDesc(desc);
            itemDescMapper.insert(itemDesc);
        }
        //发送消息（itemid 在消息中）
        //我们这里没有处理异常信息，理论上应该在catch中返回异常信息
        return BuyResult.ok();
    }

    @Override
    public List<TbItem> queryAll() {
        return itemMapper.selectList(null);
    }

    @Override
    public TbItem queryById(long itemId) {
        return itemMapper.selectById(itemId);
    }

    @Override
    public TbItemDesc queryDescById(long itemId) {
        return itemDescMapper.selectById(itemId);
    }

    @Override
    public EasyUIDatagrideVO<TbItem> queryByPage(long page, long rows) {
        Page<TbItem> itemPage = new Page<>();
        //设置每页大小
        itemPage.setSize(rows);
        //设置当前页码  内部会自动计算偏移量
        itemPage.setCurrent(page);
        //没有查询条件，所以第二个参数传null
        itemPage =  itemMapper.selectPage(itemPage,null);
        //准备一个EasyUIDatagrideVO
        EasyUIDatagrideVO<TbItem> datagrideVO = new EasyUIDatagrideVO<>();
        datagrideVO.setTotal(itemPage.getTotal());
        datagrideVO.setRows(itemPage.getRecords());
        return datagrideVO;
    }

}
